package java;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Question40 {
    public static void main(String[] args) {
        int[] candidates = {4,4,2,1,4,2,2,1,3};
        List<List<Integer>> res = combinationSum2(candidates,6);
        for (List<Integer> item: res){
            for (Integer integer : item) {
                System.out.print(integer);
            }
            System.out.println();
        }
    }
    public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if (candidates == null || candidates.length < 1 || target < 1){
            return res;
        }
        int sum = 0;
        List<Integer> useIndex = new ArrayList<>();
        List<Integer> onsRes = new ArrayList<>();
        Arrays.sort(candidates);
        combinationSum2DiGui(res,onsRes,useIndex,candidates,sum,target);
        return res;
    }

    private static void combinationSum2DiGui(List<List<Integer>> res, List<Integer> onsRes, List<Integer> useIndex, int[] candidates, int sum, int target) {
        if (sum > target) {
            return;
        }
        if (sum == target){
            res.add(new ArrayList<>(onsRes));
            return;
        }

        for (int i = 0; i < candidates.length; i++){
            if (!useIndex.isEmpty() && useIndex.get(useIndex.size() - 1) >= i){
                continue;
            }
            sum += candidates[i];
            onsRes.add(candidates[i]);
            useIndex.add(i);
            combinationSum2DiGui(res,onsRes, useIndex, candidates,sum,target);
            sum -= candidates[i];
            onsRes.remove(onsRes.size() - 1);
            useIndex.remove(useIndex.size() - 1);
            while (i + 1 < candidates.length){
                if (candidates[i] != candidates[i + 1]){
                    break;
                }
                i ++;
            }
        }
    }
}
